<template>
  <div>
    <el-card>
      <Bread first="个人中心" second="基本资料"></Bread>
      <el-form
        :model="infoForm"
        :rules="infoRuels"
        ref="infoRef"
        label-width="80px"
      >
        <el-form-item label="登录名称">
          <el-input v-model="infoForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="infoForm.nickname"></el-input>
        </el-form-item>
        <el-form-item label="用户邮箱" prop="email">
          <el-input v-model="infoForm.email"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitMod">提交修改</el-button>
          <el-button @click="resetFn">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import { updateUserInfoApi } from '../../api/user'
export default {
  data () {
    return {
      // 表单信息对象
      infoForm: {},
      // 验证规则对象
      infoRuels: {
        nickname: [
          {
            required: true,
            message: '昵称不能为空',
            trigger: ['blur']
          },
          {
            pattern: /^\S{1,10}$/,
            message: '昵称是1-10个非空字符',
            trigger: ['blur']
          }
        ],
        email: [
          {
            required: true,
            message: '邮箱不能为空',
            trigger: ['blur']
          },
          {
            pattern: /^([a-z0-9_.-]+)@([\da-z.-]+)\.([a-z.]{2,6})$/,
            message: '邮箱格式不正确',
            trigger: ['blur']
          }
        ]
      }
    }
  },
  created () {
    setTimeout(() => {
      this.infoForm = this.userInfo
      console.log(this.infoForm, '0000')
    }, 800)
  },
  computed: {
    ...mapState('user', ['userInfo'])
  },
  methods: {
    ...mapActions('user', ['AgetUserInfo']),
    // 提交修改
    submitMod () {
      this.$refs.infoRef.validate(async (valid) => {
        if (valid) {
          const res = await updateUserInfoApi(this.infoForm)
          console.log(res)
          if (res.data.code === 0) {
            this.$message.success(res.data.message)
          }
          // 修改成功之后更新页面
          this.AgetUserInfo()
        }
      })
    },
    // 重置
    resetFn () {
      this.infoForm = this.userInfo
      this.$refs.infoRef.resetFields()
    }
  }
}
</script>

<style>
.el-form {
  text-align: left;
  width: 500px;
  margin-top: 20px;
}
</style>
